-- NewBagModel

local BoxItemVo = require("app.reward.models.BoxItemVo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)
local CorePropUIHelp = require("app.coreProp.CorePropUIHelp")

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()
	self._bagInfo = nil -- 背包信息

	self._itemsAry = nil -- 分页道具集合
	self._dirtyItemsAry = nil -- 道具分页list数据发生过改变的标记(改变需要重新需要排序)
		self._allItems = nil -- 全部道具：装备、珠宝、材料、其他
		self._equips = nil -- 装备
		self._jewels = nil -- 珠宝
		self._makings = nil -- 材料
		self._others = nil -- 其他

	self._rareLists = nil -- 宝物配置集合Recast

	self._isClothesInitEnd = false 	-- 玩家所有时装分页集合初始化完毕标记
	self._clothesAry = nil -- 全部时装
	self._dirtyClothesAry = nil -- 时装分页list数据发生过改变的标记(改变需要重新需要排序)
		self._mainhandClothes = nil -- 主手
		self._offhandClothes = nil -- 副手
		self._cloakClothes = nil -- 披风
		self._maskClothes = nil -- 面具
		self._armorClothes = nil -- 盔甲
		self._helmetClothes = nil -- 头盔

	self._badgeList = nil -- 称号列表
	self._badgeChangedFlag = true -- 称号列表发生过改变(需要刷新)、默认true

	self._fameLists = nil -- 声望配置集合
	self._showAttrList = nil
	self._curRecastMaster = nil -- 当前等级强化大师属性
	self._nextRecastMaster = nil -- 下一级强化大师属性
end

function ClassRef:clearBag()
	self._bagInfo = nil

	self._itemsAry = nil
	self._dirtyItemsAry = nil
		self._allItems = nil
		self._equips = nil
		self._jewels = nil
		self._makings = nil
		self._others = nil
	self._showAttrList = nil
end

function ClassRef:initBag()
	self._allItems = {}
	self._equips = {}
	self._jewels = {}
	self._makings = {}
	self._others = {}

	self._itemsAry = {self._allItems, self._equips, self._jewels, self._makings, self._others}
	self._dirtyItemsAry = {true, true, true, true, true}

	local items = UD.bag.items
	for k,item in pairs(items) do
		if item.itemBagType == Enums.ItemBagType.equip then
			self._equips[#self._equips + 1] = item
		elseif item.itemBagType == Enums.ItemBagType.jewel then
			self._jewels[#self._jewels + 1] = item
		elseif item.itemBagType == Enums.ItemBagType.item then
			if item:isMaking() then
				self._makings[#self._makings + 1] = item
			else
				self._others[#self._others + 1] = item
			end
		end
		self._allItems[#self._allItems + 1] = item
	end

	self:initBagInfo()
end

-- 玩家会拥有的所有时装解析
function ClassRef:initAllClothes()
	------------->>>>> 初始化时装信息

	if self._isClothesInitEnd then
		return
	end

	self._mainhandClothes = {}
	self._offhandClothes = {}
	self._cloakClothes = {}
	self._maskClothes = {}
	self._armorClothes = {}
	self._helmetClothes = {}

	self._clothesAry = { self._mainhandClothes, self._offhandClothes, self._cloakClothes, self._maskClothes, self._armorClothes, self._helmetClothes }
	self._dirtyClothesAry = {true, true, true, true, true, true}

	local clothesConf = GD:queryClothesConfig()
	for _,eachClothes in pairs(clothesConf) do
		local flag = false -- 此件时装是否属于"我"
		if 0 == tonumber( eachClothes.sex ) or tonumber( Enums.Sex[UD.player.sex] ) == tonumber( eachClothes.sex ) then -- 性别满足条件
			if 0 == tonumber( eachClothes.race ) or UD.player.raceID == tonumber( eachClothes.race ) then -- 种族满足
				if string.find( eachClothes.class, ";" ) then -- 多职业
					local classIdList = string.split( eachClothes.class, ";" )
					if table.indexof( classIdList, tostring( UD.player.classID ) ) then
						flag = true
					end
				else
					if 0 == tonumber( eachClothes.class ) or UD.player.classID == tonumber( eachClothes.class ) then
						flag = true
					end
				end
			end
		end
		if flag then
			if 1 == tonumber( eachClothes.location ) then
				self._mainhandClothes[#self._mainhandClothes + 1] = tonumber(eachClothes.ID)
			elseif 2 == tonumber( eachClothes.location ) then
				self._offhandClothes[#self._offhandClothes + 1] = tonumber(eachClothes.ID)
			elseif 6 == tonumber( eachClothes.location ) then
				self._cloakClothes[#self._cloakClothes + 1] = tonumber(eachClothes.ID)
			elseif 10 == tonumber( eachClothes.location ) then
				self._maskClothes[#self._maskClothes + 1] = tonumber(eachClothes.ID)
			elseif 8 == tonumber( eachClothes.location ) then
				self._armorClothes[#self._armorClothes + 1] = tonumber(eachClothes.ID)
			elseif 5 == tonumber( eachClothes.location ) then
				self._helmetClothes[#self._helmetClothes + 1] = tonumber(eachClothes.ID)
			end
		end
	end
	self._isClothesInitEnd = true
end

function ClassRef:initBagInfo()
	local info = {}

	local coinExConf = GD:getBagConfById( UD:getBagLv() )
	local coinExNextConf = UD:isCurBagLvMax() and nil or GD:getBagConfById( UD:getBagLv() + 1 )

	info.curConf = coinExConf
	info.nextConf = coinExNextConf
	info.name = L(coinExConf.name)
	info.icon = Res.bagPath .. coinExConf.icon .. ".png"
	info.maxNum = tonumber(coinExConf.cellNum)

	self._bagInfo = info
end

-- 排序规则
-- 1、新道具优先显示（新道具具体规则见后）
-- 2、新、老道具各自按品质排序
-- 3、相同品质按装备、珠宝、材料、其它分类排序
-- 4、同品质装备按可装备等级倒序排列，同品质珠宝按强化等级排序，同品质道具按“背包排序”（关键字orderIndex）从小到大排序（留空最下）
-- 5、以上均相同的按ID排序
function ClassRef:sortItems(items)
	table.sort(items, function(a, b)
		local bagTp_a = a.itemBagType
		local bagTp_b = b.itemBagType

		local idxOf_a = nil
		if bagTp_a == Enums.ItemBagType.equip then
			idxOf_a = 1
		elseif bagTp_a == Enums.ItemBagType.jewel then
			idxOf_a = 2
		elseif bagTp_a == Enums.ItemBagType.item then
			if a:isMaking() then
				idxOf_a = 3
			else
				idxOf_a = 4
			end
		end

		local idxOf_b = nil
		if bagTp_b == Enums.ItemBagType.equip then
			idxOf_b = 1
		elseif bagTp_b == Enums.ItemBagType.jewel then
			idxOf_b = 2
		elseif bagTp_b == Enums.ItemBagType.item then
			if b:isMaking() then
				idxOf_b = 3
			else
				idxOf_b = 4
			end
		end

		if a.isNew == b.isNew then
			if a.quality == b.quality then -- 同品质
				if idxOf_a == idxOf_b then -- 同一类东西
					if bagTp_a == Enums.ItemBagType.equip then -- 装备
						if a.useLv == b.useLv then -- 装备需要的等级相同
							return a.tid > b.tid
						else
							return a.useLv > b.useLv
						end
					end
					if bagTp_a == Enums.ItemBagType.jewel then -- 珠宝
						return a.tid > b.tid
					end
					-- 道具
					if a.orderIndex == b.orderIndex then
						if a.tid == b.tid then
							return a.amount > b.amount
						else
							return a.tid > b.tid
						end
					else
						return a.orderIndex < b.orderIndex
					end
				else
					return idxOf_a < idxOf_b
				end
			else
				return a.quality > b.quality
			end
		else
			return a.isNew
		end
	end)
end

function ClassRef:sortJewels(arr)
	table.sort(arr, function(a, b)
		if a.isNew ~= b.isNew then
			return a.isNew
		elseif a.type ~= b.type then
			return a.type < b.type
		elseif a:getAttrType() ~= b:getAttrType() then
			return a:getAttrType() < b:getAttrType()
		elseif a:getLevel() ~= b:getLevel() then
			return a:getLevel() < b:getLevel()		
		elseif  tonumber( a:getQuality() ) ~= tonumber( b:getQuality() ) then
			return tonumber( a:getQuality() ) > tonumber( b:getQuality() )
		else
			return a.tid > b.tid
		end
	end)
end

-- 1	全部	self._allItems
-- 2	装备	self._equips
-- 3	宝石	self._jewels
-- 4	材料	self._makings
-- 5	其他	self._others
function ClassRef:getItemsByIdx(idx)
	if not self._itemsAry then
		self:initBag()
	end
	local ret = self._itemsAry[idx]
	if self._dirtyItemsAry[idx] then
		if idx == 3 then
			self:sortJewels(ret)
		else
			self:sortItems(ret)
		end
		self._dirtyItemsAry[idx] = false
	end
	return ret
end

-- 宝物
function ClassRef:getRareLists()
	if not self._rareLists then
		self._rareLists = GD:queryAllRestrictedRewardShow()
		local sortFunc = function( a, b )
			if a.sort == b.sort then
				return a.ID < b.ID
			else
				return a.sort < b.sort
			end
		end
		table.sort( self._rareLists, sortFunc )
	end
	return self._rareLists
end

---------------------------------------------------------------------------->>>>>>>>>>>>>> 时装相关
-- TODO 排序不停的去c++取配置，配置应该提前取好
-- 时装图纸排序
function ClassRef:_sortClothes( clothes )
	table.sort( clothes, function( a, b )
		if a == 0 then return true end
		if b == 0 then return false end
		
		local aInfo = GD:getClothesConfig(tonumber(a))
		local bInfo = GD:getClothesConfig(tonumber(b))

		local a_seat = tonumber(aInfo.quality)
		local b_seat = tonumber(bInfo.quality)

		local aIsActive = UD:isClothesActive(a)
		local bIsActive = UD:isClothesActive(b)

		local aIsNewGet = UD:isNewGetClothes(a)
		local bIsNewGet = UD:isNewGetClothes(b)

		if aIsActive and not bIsActive then
			return true
		end

		if not aIsActive and bIsActive then
			return false
		end

		if aIsNewGet and not bIsNewGet then
			return true
		end

		if not aIsNewGet and bIsNewGet then
			return false
		end

		if a_seat < b_seat then
			return true
		end

		if a_seat > b_seat then
			return false
		end

		if aInfo.type2icon and not bInfo.type2icon then
			return false
		end

		if not aInfo.type2icon and bInfo.type2icon then
			return true
		end

		if aInfo.orderIndex ~= bInfo.orderIndex then
			return tonumber(aInfo.orderIndex) < tonumber(bInfo.orderIndex)
		end

		return tonumber(aInfo.ID) < tonumber(bInfo.ID)
	end)
end

-- 设置 self._dirtyClothesAry 数据是否发生过改变
function ClassRef:setDirtyClothesAryStatus( idx, status )
	assert( idx <= #self._dirtyClothesAry, " -------------->>>>>>> setDirtyClothesAryStatus 改变状态的索引越界:" .. idx )
	status = status and true -- 不传默认true、即发生过改变，需要重新排序
	self._dirtyClothesAry[idx] = status
end

-- 时装
-- 1 	主手
-- 2 	副手
-- 3 	背
-- 4 	玩具
-- 5 	衣服
-- 6 	头盔
function ClassRef:getClothesByIdx(idx)
	if not self._clothesAry then
		self:initAllClothes()
	end

	local ret = self._clothesAry[ idx ]

	local hasNewClothes = UD.redPoint:getStateByKey(Constant.FUNC_TYPE_PACK_WARDROBE)
	if self._dirtyClothesAry[idx] or hasNewClothes then
		self:_sortClothes(ret)
		self:setDirtyClothesAryStatus( idx, false )
	end
	return ret
end

function ClassRef:clearClothesNewByIdx(idx)
	local clothesIds = self:getClothesByIdx(idx)
	local hasNew = false
	if clothesIds and #clothesIds > 0 then
	    for _,clothesId in ipairs(clothesIds) do
	        local clothes = UD:getClothesById(clothesId)
	        if clothes then
	            if clothes.isNew then
	                return true
	            end
	        else
	            break
	        end
	    end
	end
end

----------------------------------------------------------------------------<<<<<<<<<<<<<<

-- 声望信息
local fame_levelup_FameSum = 4 --fame_levelup表提供的声望总值
function ClassRef:getFameLists()
	self._fameLists = GD:getFameLists()

	-- 用玩家身上记录的声望值初始化、避免主动刷新。除了UI展开时关心，其他时候根本不关心
	for i, bigType in ipairs( self._fameLists ) do
		for k, smallType in ipairs( bigType.subDatas ) do
			local fameTemp = UD:getFameWithId( smallType.id )
			smallType.level = fameTemp.level
			smallType.exp = fameTemp.exp
		end
	end

	return self._fameLists
end

-- 背包信息
function ClassRef:getBagInfo()
	if not self._bagInfo then
		self:initBag()
	end
	return self._bagInfo
end

-- 当前道具数量
function ClassRef:getCurNum()
	if not self._itemsAry then
		self:initBag()
	end
	return #self._allItems
end

-- 当前格子最大数量
function ClassRef:getMaxNum()
	if not self._itemsAry then
		self:initBag()
	end
	return self._bagInfo.maxNum
end

function ClassRef:isBagFull()
	return self:getCurNum() >= self:getMaxNum()
end

-- 清除所有道具isNew标记
function ClassRef:clearAllNew()
	local items = UD.bag.items
	local hasNew = false
	for k,item in pairs(items) do
		if item.isNew then
			item:setIsNewGet(false)
			hasNew = true
		end
	end
	if hasNew then
		-- UD.dirty = true
	end
end

------------------------------- server -------------------------------
function ClassRef:updateBag(uid, item, amountGot, opt)
	-- print("NewBagModel.updateBag uid, pot", uid, opt)
	if not self._itemsAry then return end
	if not item then return end
	local idx
	if item.itemBagType == Enums.ItemBagType.equip then
		idx = 2
	elseif item.itemBagType == Enums.ItemBagType.jewel then
		idx = 3
	elseif item.itemBagType == Enums.ItemBagType.item then
		if item:isMaking() then
			idx = 4
		else
			idx = 5
		end
	end

	if opt == "insert" then
		local items = self._itemsAry[idx]
		items[#items + 1] = item
		self._allItems[#self._allItems + 1] = item

		self._dirtyItemsAry[idx] = true
		self._dirtyItemsAry[1] = true
	elseif opt == "delete" then
		local items = self._itemsAry[idx]
		for i,v in ipairs(items) do
			if v.uid == item.uid then
				table.remove(items, i)
				break
			end
		end

		for i,v in ipairs(self._allItems) do
			if v.uid == item.uid then
				table.remove(self._allItems, i)
				break
			end
		end
	end
	return idx
end

function ClassRef:updateBagExtend()
	if not self._bagInfo then return end
	self:initBagInfo() -- 刷新数据
end

function ClassRef:getAttrList()
	if not self._showAttrList then
		self._showAttrList = {}
		local propShowConfs = GD:querypropShow()
		local classTemp = tostring( UD:getClass())
		
		for _, v in ipairs(propShowConfs) do
			if string.find( v.roleSuit, classTemp ) then
				local conf = GD:getPropConfigByName(v.propName)
				local format = 1
				if conf then
					format = tonumber(conf.format)
				end
				table.insert( self._showAttrList, { v.propName, 0 , format} )
			end
		end
	end
	return self._showAttrList
end

function ClassRef:updateAttrList(prop)
	local showAttrList = self:getAttrList()
	for k, v in pairs(showAttrList) do
		if v[1] == "baseattackspeed" then
			v[2] = GD:queryProBase(UD:getClass()).baseattackspeed
		else
			local propValue = rawget(prop, v[1]) or 0
			v[2] = propValue
		end
	end
end

function ClassRef:hasNewItem()
	if not self._allItems then
		return  false
	end
	for i,v in ipairs(self._allItems) do
		if v.isNew then
			return true
		end
	end
	return false
end

--强化大师信息
function ClassRef:setRecastMaster(nowId, nextId)
	local function initRecastMaster(id)
		local conf = GD:getRecastMasterById(id)
		local classId = UD:getClass() 
		if not conf then return end
		local list = {}
		if conf["class"..classId] then
			local ret = string.splitTwice(conf["class"..classId], {";", "|"}, true)
			local info = {}
			for _, v in ipairs(ret) do
				local propConf = GD:getPropConfig(v[1])
				local propName = propConf and L(propConf.name) or L(v[1])
				local propFormat = propConf and tonumber(propConf.format)
				table.insert(info, {name= propName, num= v[2], format = propFormat})
			end
			list.targetLv = tonumber(conf.lvEquip)
			list.propInfo = info
		end
		return list
	end
	self._curRecastMaster = initRecastMaster(nowId)
	self._nextRecastMaster = initRecastMaster(nextId)
	-- 刷新强化大师红点(登录的时候不判断小红点)
	if self._nowId ~= nowId then
		if self._nowId then
			UD.redPoint:setStateByKey(RedPointConstant.RecastMonster_Exchange, true)
		end
		self._nowId = nowId
	end
end

function ClassRef:getRecastMaster()
	return self._curRecastMaster, self._nextRecastMaster
end

----------------------------- request --------------------------------
function ClassRef:reqSortItem() -- 背包排序
	app.session:request("action.C2S_SortItem", {}, function(ret)
		app:popMessage( "sortcomplete" )
	end)
end

function ClassRef:reqSellItem(uids, amounts) -- 出售、可以成组出售
	app.session:request("action.C2S_SellItem", {uid=uids, amount=amounts}, function(ret)
		app:popMessage( "sellsuccess" )
		app:sendMsg("NewBagController", "closeMultPanle") -- 通知关闭 BagMultPanel
		app:sendMsg("NewBagController", "clearTips")
	end)
end

-- -- 分解道具
-- function ClassRef:reqBreakItem(uids) -- 分解、可以成组分解
-- 	app.session:request("action.C2S_BreakItem", {uid=uids}, function(ret)
-- 		dump(ret, "NewBagModel.reqBreakItem")
-- 		app:sendMsg("NewBagController", "closeMultPanle") -- 通知关闭 BagMultPanel
-- 		app:sendMsg("NewBagController", "clearTips")
-- 	end)
-- end

-- 分解道具、装备、珠宝、符文
function ClassRef:reqBreakItems( itemsList )
	app.session:request("action.C2S_BreakItem", { items = itemsList }, function(ret)
		app:sendMsg("NewBagController", "playBreakSuccessAnim")
		app:sendMsg("NewBagController", "closeMultPanle") -- 通知关闭 BagMultPanel
		app:sendMsg("NewBagController", "clearTips")
	end, nil,
	function(errMsg)
		app:sendMsg("NewBagController", "breakFailed")
		app:sendMsg("NewBagController", "closeMultPanle")
		app:sendMsg("NewBagController", "clearTips")
		return false
	end)
end

-- 鉴定道具
function ClassRef:reqIdentifyItem(uids)
	app.session:request("action.C2S_Identify", {uids=uids}, function(ret)
		if ret.ok then
			app:popMessage("appraisalsuccsee")
		end
	end)
end

function ClassRef:reqRenamePlayer(str)
	app.session:request("action.C2S_ChangeUserName", {userName = str}, function(ret)
		if ret.ok then
			display.pushToast(L("rename4"))
		end
	end,{block = true})
end

function ClassRef:reqRenameGuild(data)
	app.session:request("pb_guild.C2S_ChangeGuildName", {newName = data.name,flagBaseIcon = data.flagBaseIcon,
		flagAdditionalIcon = data.flagAdditionalIcon,flagBaseIconColor = data.flagBaseIconColor,flagAdditionalIconColor = data.flagAdditionalIconColor}, function(ret)
		if ret.ok then
			display.pushToast(L("rename4"))
		end
	end,{block = true})
end


-- 使用道具
function ClassRef:reqUseItem(uid, tid, amount, cb, errCb)
	if tid == Constant.Rename_Player_Card then
		app:sendMsg("NewBagController", "showRenamePlayerView")
		return
	elseif tid == Constant.Rename_Guild_Card then
		if UD:isInGuild() and UD:isGuildLeader() then
			app:sendMsg("NewBagController", "showRenameGuildView")
		else
			display.pushToast(L("rename6"))
		end
		return
	end
	-- 检测是否包含赠送钻石，如果包含需要考虑是否有midas权限
	if not app:isMidasPermissionOK() and GD:checkItemHasPresentCoin(tid) then
		app:getRunningScene():openMidasPermissionDlg(L("warrantExpired"))
		return
	end

	app.session:request("action.C2S_UseItem", {uid=uid, amount=amount}, function(ret)
		executeFunc(cb, ret.ok)
		if ret.ok then
			app:popMessage( "useitem" )

			if ret.luckItems then -- 显示luckBox
				local items = {0,0,0,0,0}
				for i,v in ipairs(ret.luckItems) do
					items[i] = BoxItemVo.new(v)
				end
				items = table.randomCnt(items)
				app:sendMsg("BoxController", "onOpenBox", items)
			else
				local conf = GD:queryItemById(tid)
				if conf then
					if tonumber(conf.type) == 4 then -- 图纸、配方
						if UD.badge:setNum(Constant.FUNC_TYPE_COMPOUND,1) then
							-- UD.dirty = true
						end
						app:popMessage( "addfomula", {L(conf.name)} )
					elseif tonumber(conf.type) ==12 then  --任务获取
						-- do nothing
					end
				end
			end
		end
	end, nil, function(err)
		executeFunc(cb, false)
		executeFunc(errCb)
	end)
end

function ClassRef:reqExtendBag()
	app.session:request("pb_bag.C2S_ExtendBag", {}, function(ret)
		if ret.ok then
			app:popMessage( "bagupdatasuccess" )
		else
			app:popMessage( L("lua_code_text_360") )
		end
	end)
end

function ClassRef:confirmReqEquipEquipmentX(equipData, cb)
	local curEquip = UD:getEquipByPos(equipData:getPos())
	local hasJewel = false
	if curEquip then
		hasJewel = curEquip:isEquipHasJewel()
	end

	self:confirmReqEquipEquipment(equipData.uid, equipData.tid, cb, hasJewel)
end

function ClassRef:confirmReqEquipEquipment(uid, tid, cb, hasJewel)
	if not hasJewel then
		return self:reqEquipEquipment(uid, tid, cb)
	end

	local confirmDialog = display.newConfirmDialog(L("bag_equip_jewel_confirm"),
			function()
				self:reqEquipEquipment(uid, tid, cb, true)
			end,
			function()
				self:reqEquipEquipment(uid, tid, cb, false)
			end)

	confirmDialog:setConfirmText(L("tips_ok"))
	confirmDialog:setCancelText(L("tips_cancel"))
	UIHandler:addPopDialog(confirmDialog, 1, true)
end
 -- 穿装备
function ClassRef:reqEquipEquipment(uid, tid, cb, bRemoveJewel)
	app.session:request("action.C2S_EquipEquipment", {uid=uid, isRemoveJewel=bRemoveJewel}, function(ret)
        AM.playChangeEquipSound()
        app:popMessage("equipsuccess", {pushToast=true})
        if ret.oper then
            UD:apply(ret.oper,true,true)
        end
        executeFunc(cb, false)
	end, nil, function(err)
		executeFunc(cb, false)
	end)
end

function ClassRef:confirmReqUnEquipEquipment(uid, tid, hasJewel)
	if not hasJewel then
		self:reqUnEquipEquipment(uid, tid)
		return 
	end

	local confirmDialog = display.newConfirmDialog(L("bag_equip_jewel_confirm"),
			function()
				self:reqUnEquipEquipment(uid, tid, true)
			end,
			function()
				self:reqUnEquipEquipment(uid, tid, false)
			end)

	confirmDialog:setConfirmText(L("tips_ok"))
	confirmDialog:setCancelText(L("tips_cancel"))
	UIHandler:addPopDialog(confirmDialog, 1, true)
end

-- 卸装备
function ClassRef:reqUnEquipEquipment(uid, tid, bRemoveJewel)
	app.session:request("action.C2S_UnEquipEquipment", {uid=uid, isRemoveJewel=bRemoveJewel}, function(ret)
		if ret.oper then
            UD:apply(ret.oper,true,true)

        end
	end)
end

-- 装备幻化
-- 0=success, 1=no equip, 2=no fashion, 3=same fashion, 4=class limit,
-- 5=race limit, 6=gender limit, 7=lack consume, 8=location error


-- 上面装备幻化应该不用了----------------------------
function ClassRef:reqEquipFashion( clothesID )
	app.session:request("pb_fashion.C2S_EquipFashion", {fashionID=clothesID}, function(ret)
		if ret.ok then -- 成功？
			display.pushToast( L("fashion_success") )
            local conf = GD:getClothesConfig(clothesID)
            if conf and tonumber(conf.location) == Enums.EquipType.head then
                local equipGrid = UD:getEquipGridByPos(Enums.EquipType.head)
                local isHidden = equipGrid:getHidden() 
                 if isHidden then
                    display.pushToast( L("hide_helmet_tips") )
                 end
            end
		end
	end)
end

function ClassRef:reqRemoveFashion( clothesID )
	app.session:request("pb_fashion.C2S_RemoveFashion", {fashionID=clothesID}, function(ret)
		if ret.ok then -- 成功？
			display.pushToast( L("fashion_cancel") )
		end
	end)
end


-- 装备属性转移
function ClassRef:reqTransEquipAttr( data )
	-- dump( data, " -------------->>>>>> reqTransEquipAttr " )

	app.session:request("action.C2S_MoveEquipExtraProp", { sourceUUID = data[1], targetUUID = data[2],	moveIndexes = data[3] }, function(ret)
		-- dump( ret, " -------------->>>>>> reqTransEquipAttr ret" )
		if ret.ok then
			display.pushToast( L("lua_code_text_83") )
			app:sendMsg("NewBagController", "clearTips")
			app:sendMsg("NewBagController", "attrTransSuccessCallback", data[1])
		end
	end)
end

-- 属性条卷轴属性转移
function ClassRef:reqAddEquipExtraProp( data )
	-- dump( data, "------------------->>>> reqAddEquipExtraProp")

	app.session:request("action.C2S_AddEquipExtraProp", { itemId = data[1], equipUUID = data[2], transIndex = data[3]}, function(ret)
		-- dump(ret, "-------------------->>> reqAddEquipExtraProp ret")
		if ret.ok then
			display.pushToast(L("lua_code_text_83"))
			app:sendMsg("NewBagController", "clearTips")
		end
	end)
end

-- 切换称号
function ClassRef:reqChangeTitle( titleTemp )
	local idChangeTo = nil
	if UD:isTitleActive( titleTemp:getId() ) then
		idChangeTo = 0
	else
		idChangeTo = tonumber( titleTemp:getId() )
	end
	UD:reqActiveTitle( idChangeTo )
end

-- 装备格子强化
local lastReqTimeStamp = 0 -- 上次发送此请求的时间戳
local ReqTimeOffset = 0.5
local lastPostTimeStamp = 0 -- 上次弹提示的时间戳
local PostTimeOffset = 1

local lastReqStrengthTen = 0
function ClassRef:reqStrengthEquipGrid( equipUid )
	local curtime = app:getTime()
	if ReqTimeOffset > curtime - lastReqTimeStamp then -- 发送过快
		if PostTimeOffset <= curtime - lastPostTimeStamp then
			--display.pushToast( L("请求过快，请先休息一下！") )
			lastPostTimeStamp = curtime
		end
		return
	end
	lastReqTimeStamp = curtime
	app.session:request("action.C2S_Recast", {uid=equipUid}, function(ret)
		if ret and ret.ok then -- 成功
			display.pushToast( L("lua_code_text_428") )
			app:sendMsg("NewBagController", "playStrengthSuccessAmi")
		else
			-- display.pushToast( L("强化失败") )
			-- local dialog = display.newMessageBox("强化失败，下次强化概率提升5%")
			-- UIHandler:addPopupUi(dialog)
			app:sendMsg("NewBagController", "playStrengthFailAmi")
		end
		app:sendMsg("NewBagController", "refreshEquipStrengthResult", equipUid)
	end)
end

function ClassRef:reqStrengthEquipGridTen( equipUid )
	local curtime = app:getTime()
	if curtime - lastReqStrengthTen < 1 then
		return
	end
	lastReqStrengthTen = curtime

	app.session:request("action.C2S_RecastBatch", {uid=equipUid}, function(ret)
		local success = rawget(ret, "success") or 0 
		local failed = rawget(ret, "failed") or 0

		local str = ""
		if success > 0 then
			str = str .. string.format(L("StrengthTenTipSuccess"), success)
		end

		if success >0 and failed > 0 then
			str = str .. ", "
		end

		if failed > 0 then
			str = str .. string.format(L("StrengthTenTipFail"), failed)
		end
		if success + failed > 0 then
			display.pushToast( str )
			if  success > 0 then
				app:sendMsg("NewBagController", "playStrengthSuccessAmi")
			else
				if failed > 0 then
					app:sendMsg("NewBagController", "playStrengthFailAmi")
				end
			end
		else
			app:sendMsg("NewBagController", "playStrengthFailAmi")
		end
		app:sendMsg("NewBagController", "refreshEquipStrengthResult", equipUid)
	end)
end

--请求一键强化
function ClassRef:reqQuickStrength()
	app.session:request("action.C2S_RecastAllIn", {}, function(ret)
		local success = rawget(ret, "success") or 0
		local failed = rawget(ret, "failed") or 0
		local equipGridIds = {}
		for k,v in ipairs(ret.locs) do
			table.insert(equipGridIds, v)
		end

		dump(ret)
		local str = ""
		if success > 0 then
			str = str .. string.format(L("StrengthTenTipSuccess"), success)
		end

		if success >0 and failed > 0 then
			str = str .. ", "
		end

		if failed > 0 then
			str = str .. string.format(L("StrengthTenTipFail"), failed)
		end
		if success + failed > 0 then
			display.pushToast( str )
			if  success > 0 then
				--app:sendMsg("NewBagController", "playStrengthSuccessAmi")
			else
				if failed > 0 then
					--app:sendMsg("NewBagController", "playStrengthFailAmi")
				end
			end
		else
			display.pushToast(L("partnerString7"))
			--app:sendMsg("NewBagController", "playStrengthFailAmi")
		end

		app:sendMsg("NewBagController", "refreshPlayerPanelAfterQuickStrength", ret.locs)
	end,{block = true})
end



-- 查属性
function ClassRef:reqQueryMyProp()
	app.session:request("pb_query.C2S_QueryMyProp", {}, function(ret)
		if ret.prop then
			self:updateAttrList(ret.prop)
			app:sendMsg("NewBagController", "updateProp", self:getAttrList())
		end
	end)
end

-- 隐藏头盔
function ClassRef:reqHideFashion(hiddenList)
     app.session:request("pb_fashion.C2S_HideFashion",{hiddenInfo = hiddenList},function(ret)
         local equipGrid = UD:getEquipGridByPos(Enums.EquipType.head) 
         local isHidden = equipGrid:getHidden() 
         if isHidden then
            display.pushToast(L("hide_helmet_hidesucceed"))
         else
            display.pushToast(L("hide_helmet_showsucceed"))
         end
     end)
end

-- 强化大师
function ClassRef:reqQueryRecastMaster()
	app.session:request("action.C2S_QueryRecastMaster", {})
end

return ClassRef
